package com.ocom.aiotweb.config;

import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

/**
 * 资源服务配置
 *
 */
@Configuration
@EnableResourceServer
@AllArgsConstructor
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

	private final TokenStore tokenStore;

	/**
	 * token服务配置
	 */
    @Override
	public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
		//这里把自定义异常加进去
		resources.tokenStore(tokenStore).authenticationEntryPoint(new AuthExceptionEntryPoint())
				.accessDeniedHandler(new CustomAccessDeniedHandler());
	}

	/**
	 * 路由安全认证配置
	 */
	@Override
	public void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests()
				// 配置hello打头的路由需要安全认证，order无配置无需认证
				.antMatchers("/hello/**").authenticated()
				.and().csrf().disable();
	}

	/**
	 * jwt token 校验解析器
	 */
	@Bean
	public TokenStore tokenStore(JwtAccessTokenConverter accessTokenConverter) {
		return new JwtTokenStore(accessTokenConverter);
	}

	/**
	 * Token转换器必须与认证服务一致
	 */
//

	/**
	 * 资源服务令牌解析服务
	 */
//	@Bean
//	@Primary
//	public ResourceServerTokenServices tokenServices() {
//        RemoteTokenServices remoteTokenServices = new RemoteTokenServices();
//        remoteTokenServices.setAccessTokenConverter(accessTokenConverter());
////        remoteTokenServices.setCheckTokenEndpointUrl("http://localhost:8081/oauth/check_token");
////        remoteTokenServices.setClientId("client_1");
////        remoteTokenServices.setClientSecret("123456");
//        return remoteTokenServices;
//	}
}
